﻿using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Reflection;

namespace Entities.Operate
{
    public class Member : Interface.IMember
    {
        private Data.IRepository<Entities.Member> mRepository = new Repository<Entities.Member>().GetRepository;//new Data.MongoDb.MongoRepository<Entities.Member>();//
        public Entities.Member GetById(ObjectId Id)
        {
            return mRepository.Get(Id);
        }

        public IEnumerable<Entities.Member> GetByUserName(string username)
        {
            QueryDocument query = new QueryDocument();
            BsonDocument b = new BsonDocument();
            b.Add("UserName", username);
            query.AddRange(b);
            return mRepository.Find(query);
        }

        public IEnumerable<Entities.Member> GetMembers()
        {
            return mRepository.AsQueryable();
        }

        public IEnumerable<Entities.Member> FindAs(QueryDocument query)
        {
            return mRepository.Find(query);
        }

        public bool Update(Entities.Member args)
        {
            try
            {
                //var fiter = Builders<Entities.Member>.Filter.Eq("Id", args.Id);
                //IList<UpdateDefinition<Entities.Member>> update = new List<UpdateDefinition<Entities.Member>>();
                //foreach (PropertyInfo p in args.GetType().GetProperties())
                //{
                //    if (!p.Name.Equals("Id"))
                //        update.Add(Builders<Entities.Member>.Update.Set(p.Name, p.GetValue(args)));
                //}
                //mRepository.Update(fiter, Builders<Entities.Member>.Update.Combine(update));
                mRepository.Update(args);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Insert(Entities.Member args)
        {
            mRepository.Insert(args);
        }

        public bool Delete(Entities.Member args)
        {
            try
            {
                
                mRepository.DeleteById(ObjectId.Parse(args.Id.ToString()));
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
